from django.http import Http404, HttpResponse
from django.core.cache import cache
import erlydb
from simplereg.models import CouchDBServer
import simplejson

def _get_links(url):
    interface = erlydb.ErlySocialInterface(CouchDBServer.objects.get_url())
    friend_urls = interface.get_friends_from_url(url)
    to_return = []
    for friend_url in friend_urls:
        friend_identity_urls = interface.get_identity_urls(friend_url)
        friend_identity_urls.sort()
        id = friend_identity_urls[0]
        for friend_identity_url in friend_identity_urls:
            to_return.append({'id':id, 'url':friend_identity_url})
    return to_return

def visualization_json(request):
    url = request.GET.get('url', None)
    if url is None:
        raise Http404
    response = cache.get("json_%s" % url)
    if not response:
        print "Didn't have it in the cache"
        response = HttpResponse(simplejson.dumps(_get_links(url)), 
        #    mimetype="application/json"
        )
        cache.set("json_%s" % url, response, 60*2)
    return response

def visualization_xml(request):
    url = request.GET.get('url', None)
    if url is None:
        raise Http404
    response = cache.get("xml_%s" % url)
    if not response:
        print "Didn't have it in the cache"
        interface = erlydb.ErlySocialInterface(CouchDBServer.objects.get_url())
        identity_urls = interface.get_identity_urls(url)
        identity_urls.sort()
        xml = '<?xml version="1.0" ?><items id="%s">' % identity_urls[0]
        for link_dict in _get_links(url):
            xml += '<item id="%s">%s</item>' % (link_dict['id'], link_dict['url'])
        xml += "</items>"
        response = HttpResponse(xml, 
            mimetype="application/xml"
        )
        cache.set("xml_%s" % url, response, 60*2)
    return response